<%
	local api = require "luci.model.cbi.passwall.api.api"
	local dsp = require "luci.dispatcher"
	
	local tcp_node_num = api.uci_get_type("global_other", "tcp_node_num", 1)
	local udp_node_num = api.uci_get_type("global_other", "udp_node_num", 1)
	local socks5_node_num = api.uci_get_type("global_other", "socks5_node_num", 1)
-%>

<style>
table th, .table .th {
	text-align: center;
}

table td, .table .td {
	text-align: center;
}

#set_node_div{
	display: none;
	width: 30rem;
	position: absolute;
	left:50%;
	top:50%;
	transform: translate(-50%, -50%);
	padding-top: 30px;
	z-index: 99;
	text-align: center;
	background: white;
    box-shadow: darkgrey 10px 10px 30px 5px;
}
</style>

<script type="text/javascript">
	//<![CDATA[
	var section = "";
	function open_set_node_div(cbi_id) {
		section = cbi_id;
		document.getElementById("set_node_div").style.display="block";
	}
	
	function close_set_node_div() {
		document.getElementById("set_node_div").style.display="none";
	}
	
	
	var auto_ping_value = document.getElementsByClassName('auto_ping_value');
	for(var i = 0; i < auto_ping_value.length; i++) {
		XHR.get('<%=dsp.build_url("admin/vpn/passwall/auto_ping_node")%>', {
				index: i,
				domain: auto_ping_value[i].getAttribute("server")
			},
			function(x, result) {
				auto_ping_value[result.index].innerHTML = (result.ping ? result.ping : "--") + " ms";
			}
		);
	}
	
	function set_node(protocol,number) {
		if (confirm('<%:Are you sure set to%> ' + protocol.toUpperCase() + "_" + number + '<%:the server?%>')==true){
			XHR.get('<%=dsp.build_url("admin/vpn/passwall/set_node")%>', { "protocol" : protocol , "number" : number , "section" : section },
				function(x, result) {
					if(x && x.status == 200) {
						window.location.href = '<%=dsp.build_url("admin/vpn/passwall/log")%>'
					}
				}
			);
		}
	}
	
	function ping_node(node,dom) {
		XHR.get('<%=dsp.build_url("admin/vpn/passwall/ping_node")%>', { "node" : node },
			function(x, result) {
				if(x && x.status == 200) {
					dom.outerHTML = result.ping + " ms";
				}
			}
		);
	}
	//]]>
</script>

<div id="set_node_div">
	<div class="cbi-value">
		<% if tcp_node_num and tonumber(tcp_node_num) >= 1 then %>
			<% for i = 1, tcp_node_num, 1 do %>
				<input class="cbi-button cbi-button-edit" type="button" onclick="set_node('tcp',<%=i%>)" value="TCP_<%=i%>">
			<% end %>
		<% end %>
		
		<% if udp_node_num and tonumber(udp_node_num) >= 1 then %>
			<% for i = 1, udp_node_num, 1 do %>
				<input class="cbi-button cbi-button-edit" type="button" onclick="set_node('udp',<%=i%>)" value="UDP_<%=i%>">
			<% end %>
		<% end %>
		
		<% if socks5_node_num and tonumber(socks5_node_num) >= 1 then %>
			<% for i = 1, socks5_node_num, 1 do %>
				<input class="cbi-button cbi-button-edit" type="button" onclick="set_node('socks5',<%=i%>)" value="Socks5_<%=i%>">
			<% end %>
		<% end %>
		<input class="cbi-button cbi-button-remove" type="button" onclick="close_set_node_div()" value="<%:Close%>">
	</div>
</div>